{% extends "score/base.html" %}

{% block title %}{{ title }} - ExamPulse{% endblock %}

{% block score_content %} <!-- 原 scores_content → score_content -->
<div class="row justify-content-center">
    <div class="col-md-10">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0">
                    <i class="fas fa-plus-square me-2"></i>{{ title }}
                    <a href="{% url 'score:score_add' %}" class="btn btn-light btn-sm float-end"> <!-- 原 scores: → score: -->
                        <i class="fas fa-plus me-1"></i>单科添加
                    </a>
                </h4>
            </div>
            <div class="card-body">
                <form method="post" id="scoreFormMultiple">
                    {% csrf_token %}
                    {{ formset.management_form }}

                    {% if formset.non_form_errors %}
                    <div class="alert alert-danger">
                        {% for error in formset.non_form_errors %}
                        <p class="mb-0">{{ error }}</p>
                        {% endfor %}
                    </div>
                    {% endif %}

                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th>考试</th>
                                    <th>科目</th>
                                    <th>得分</th>
                                    <th>考试用时(分钟)</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for form in formset %}
                                <tr class="score-form-row">
                                    <td>
                                        {{ form.exam }}
                                        {% if form.exam.errors %}
                                        <div class="text-danger small mt-1">
                                            {% for error in form.exam.errors %}
                                            <p class="mb-0">{{ error }}</p>
                                            {% endfor %}
                                        </div>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {{ form.subject }}
                                        {% if form.subject.errors %}
                                        <div class="text-danger small mt-1">
                                            {% for error in form.subject.errors %}
                                            <p class="mb-0">{{ error }}</p>
                                            {% endfor %}
                                        </div>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {{ form.score }}
                                        {% if form.score.errors %}
                                        <div class="text-danger small mt-1">
                                            {% for error in form.score.errors %}
                                            <p class="mb-0">{{ error }}</p>
                                            {% endfor %}
                                        </div>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {{ form.exam_duration }}
                                        {% if form.exam_duration.errors %}
                                        <div class="text-danger small mt-1">
                                            {% for error in form.exam_duration.errors %}
                                            <p class="mb-0">{{ error }}</p>
                                            {% endfor %}
                                        </div>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-danger remove-row"
                                                {% if forloop.first %}style="visibility: hidden;"{% endif %}>
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-3">
                        <button type="button" id="addMore" class="btn btn-outline-primary">
                            <i class="fas fa-plus me-1"></i>添加更多
                        </button>
                        <button type="submit" class="btn btn-primary ms-2">
                            <i class="fas fa-save me-1"></i>保存所有成绩
                        </button>
                        <a href="{% url 'score:score_list' %}" class="btn btn-outline-dark ms-2"> <!-- 原 scores: → score: -->
                            <i class="fas fa-times me-1"></i>取消
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 当文档加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 添加更多行按钮
    document.getElementById('addMore').addEventListener('click', function() {
        // 克隆第一行（但不包括错误信息）
        const totalForms = document.getElementById('id_form-TOTAL_FORMS');
        const formCount = parseInt(totalForms.value);
        const firstRow = document.querySelector('.score-form-row');
        const newRow = firstRow.cloneNode(true);

        // 更新新行中所有字段的ID和name
        const inputs = newRow.querySelectorAll('input, select');
        inputs.forEach(function(input) {
            const name = input.name.replace(/form-\d+-/, `form-${formCount}-`);
            input.name = name;
            input.id = `id_${name}`;
            input.value = ''; // 清空值

            // 移除错误信息和样式
            input.classList.remove('is-invalid');
            const errorDiv = input.parentNode.querySelector('.text-danger');
            if (errorDiv) {
                errorDiv.remove();
            }
        });

        // 显示删除按钮
        const removeBtn = newRow.querySelector('.remove-row');
        removeBtn.style.visibility = 'visible';
        removeBtn.addEventListener('click', function() {
            newRow.remove();
            updateFormCount();
        });

        // 添加到表格
        firstRow.parentNode.appendChild(newRow);

        // 更新表单计数
        totalForms.value = formCount + 1;
    });

    // 为现有的删除按钮添加事件监听
    document.querySelectorAll('.remove-row').forEach(function(btn) {
        btn.addEventListener('click', function() {
            if (document.querySelectorAll('.score-form-row').length > 1) {
                btn.closest('.score-form-row').remove();
                updateFormCount();
            }
        });
    });

    // 初始化科目选择框的联动
    document.querySelectorAll('select[name$="-exam"]').forEach(function(examSelect) {
        examSelect.addEventListener('change', function() {
            const row = this.closest('.score-form-row');
            const subjectSelect = row.querySelector('select[name$="-subject"]');
            updateSubjectOptions(this.value, subjectSelect);
        });
    });
});

// 更新表单计数
function updateFormCount() {
    const totalForms = document.getElementById('id_form-TOTAL_FORMS');
    const rows = document.querySelectorAll('.score-form-row');
    totalForms.value = rows.length;

    // 更新所有行的索引
    rows.forEach(function(row, index) {
        const inputs = row.querySelectorAll('input, select');
        inputs.forEach(function(input) {
            const name = input.name.replace(/form-\d+-/, `form-${index}-`);
            input.name = name;
            input.id = `id_${name}`;
        });
    });
}

// 更新科目选项
function updateSubjectOptions(examId, subjectSelect) {
    if (!examId) return;

    // 原 /scores/ajax/ → /score/ajax/（URL路径中的scores改为score）
    fetch(`/score/ajax/get-exam-subjects/?exam_id=${examId}`)
        .then(response => response.json())
        .then(subjects => {
            // 保存当前选中的值
            const currentValue = subjectSelect.value;
            
            // 清空现有选项（保留第一个空选项）
            while (subjectSelect.options.length > 1) {
                subjectSelect.remove(1);
            }
            
            // 添加新选项
            subjects.forEach(subject => {
                const option = document.createElement('option');
                option.value = subject.id;
                option.textContent = subject.name;
                subjectSelect.appendChild(option);
            });
            
            // 恢复之前选中的值（如果存在）
            if (currentValue && Array.from(subjectSelect.options).some(opt => opt.value === currentValue)) {
                subjectSelect.value = currentValue;
            }
        })
        .catch(error => {
            console.error('获取科目数据失败:', error);
        });
}
</script>
{% endblock %}